package com.mifengs.mall.ui.openself;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.entity.StoreApplyInfo;
import com.mifengs.mall.event.OpenSelfEvent;
import com.mifengs.mall.ui.opencompany.AuditFragment;
import com.mifengs.mall.widget.StepsViewIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OpenSelfActivity extends BaseActivity {
    @BindView(R.id.step_view)
    StepsViewIndicator mStepView;
    @BindView(R.id.error_info_text)
    TextView errorInfoText;
    @BindView(R.id.relative_error)
    RelativeLayout relativeError;
    private String[] mStepTexts = new String[]{"提交资质", "手写签名", "资质审核"};
    private Fragment mCurrentFragment;
    private Fragment mMaterialSubFragment;
    private Fragment mHandWriteFragment;
    private AuditFragment mAuditFragment;
    private StoreApplyInfo mInfo;
    private   ShowErrorThread errorThread;
    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    relativeError.setVisibility(View.GONE);
                    isShowNavigationBar(true);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_self);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        setStatusColorAndMode(R.color.white, true);
        initNavigationBar(true, "提交资质");
        init(savedInstanceState);
    }

    private void init(Bundle savedInstanceState) {
        mStepView.setStepTexts(mStepTexts);
        mMaterialSubFragment = MaterialSubFragment.newInstance(0, false);
        mCurrentFragment = mMaterialSubFragment;
        if (savedInstanceState == null) {
            FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
            ft.add(R.id.container, mCurrentFragment).commit();
        }
        mInfo = (StoreApplyInfo) getIntent().getSerializableExtra("StoreApplyInfo");
        if (mInfo != null) {
            int storeStatus = mInfo.getStoreApplyInfoDto().getStoreStatus();
            handleStatus(storeStatus);
        } else {
            mStepView.setCompletedPosition(0, false);
        }
    }

    private void handleStatus(int storeStatus) {
        if (storeStatus == 1) {
            toAuditPage(AuditFragment.AuditStatus.AuditSuccess); //正常上线
        } else if (storeStatus == 5) {     //初审不通过
            toAuditPage(AuditFragment.AuditStatus.AuditFail);
        } else if (storeStatus == -1) {    //等待初审
            toAuditPage(AuditFragment.AuditStatus.AuditIng);
        } else if (storeStatus == -2) {  //拒绝
            toAuditPage(AuditFragment.AuditStatus.AuditRefuse);
        } else if(storeStatus == 0){ //下线
            toAuditPage(AuditFragment.AuditStatus.AuditClose);
        } else if(storeStatus == -3){ //店铺关闭
            toAuditPage(AuditFragment.AuditStatus.AuditClose);
        }
    }

    private void switchContent(Fragment from, Fragment to) {
        if (mCurrentFragment != to) {
            mCurrentFragment = to;
            FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from).add(R.id.container, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    private void toMaterialSubPage(boolean fail) {
        mMaterialSubFragment = MaterialSubFragment.newInstance(0, fail);
        this.switchContent(mCurrentFragment, mMaterialSubFragment);
        mStepView.setCompletedPosition(0, StepsViewIndicator.StepStatus.steping);
    }

    private void toAuditPage(AuditFragment.AuditStatus status) {
        if (mInfo != null) {
            mAuditFragment = AuditFragment.newInstance(status, mInfo.getStoreApplyInfoDto().getStoreAudit(), false, true);
        } else {
            mAuditFragment = AuditFragment.newInstance(status, "", false, true);
        }
        switch (status) {
            case AuditIng:
                mStepView.setCompletedPosition(2, StepsViewIndicator.StepStatus.steping);
                break;
            case AuditRefuse:
            case AuditFail:
                mStepView.setCompletedPosition(2, StepsViewIndicator.StepStatus.stepFail);
                break;
            case AuditSuccess:
                mStepView.setCompletedPosition(2, StepsViewIndicator.StepStatus.stepSuccess);
                break;
            case AuditClose:
                mStepView.setCompletedPosition(2, StepsViewIndicator.StepStatus.stepSuccess);
                break;
        }

        mStepView.setStepTexts(mStepTexts);
        this.switchContent(mCurrentFragment, mAuditFragment);
    }

    private void toHandWritePage(HashMap<String, Object> hashMap) {
        mHandWriteFragment = HandWriteFragment.newInstance(hashMap);
        mStepView.setCompletedPosition(1, false);
        mStepView.setStepTexts(mStepTexts);
        this.switchContent(mCurrentFragment, mHandWriteFragment);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenSelfEvent event) {
        switch (event.action) {
            case OpenSelfEvent.TOMATERIALSUBPAGE:
                toMaterialSubPage(false);
                break;
            case OpenSelfEvent.TOHANDWRITEPAGE:
                toHandWritePage(event.getHashMap());
                break;
            case OpenSelfEvent.TOAUDITPAGE:
                toAuditPage(event.auditStatus);
                break;
            case OpenSelfEvent.TOMATERIALSUBPAGE_FAIL:
                setErrorInfo();
                toMaterialSubPage(true);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.HANDWRITE_RESULT) {
            if(mHandWriteFragment != null){
                mHandWriteFragment.onActivityResult(requestCode, resultCode, data);
            }
        } else {
            if(mMaterialSubFragment != null){
                mMaterialSubFragment.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if(errorThread !=null){
            try {
                errorThread.interrupt();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

    private void setErrorInfo() {
        isShowNavigationBar(false);
        relativeError.setVisibility(View.VISIBLE);
        if (mInfo != null) {
            errorInfoText.setText(mInfo.getStoreApplyInfoDto().getStoreAudit() + "  !");
        }
        errorThread = new ShowErrorThread();
        errorThread.start();

    }

    public class ShowErrorThread extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message msg = new Message();
            msg.what = 1;
            mHandle.sendMessage(msg);
        }
    }

    protected void initNavigationBar(boolean isBackVisible, String title) {
        RelativeLayout llNavBar = (RelativeLayout) this.findViewById(R.id.navigation_bar);
        if (llNavBar != null) {
            LinearLayout llBack = (LinearLayout) this.findViewById(R.id.ll_back);
            llBack.setVisibility(isBackVisible ? View.VISIBLE : View.INVISIBLE);
            llBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(mCurrentFragment instanceof MaterialSubFragment){
                        leave();
                    }else{
                        finish();
                    }

                }
            });
            TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
            tvTitle.setText(title);
        }
    }



    private void leave(){
        AlertDialog.Builder builder =  new AlertDialog.Builder(this);
        builder.setTitle("是否需要保存")
                .setPositiveButton("是",new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ((MaterialSubFragment)mCurrentFragment).saveData();
                        finish();
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferenceUtils.saveBooleanPreference(getContext(),MaterialSubFragment.IS_SAVE,false);
                        finish();
                    }
                }).create().show();
    }


}
